#!/usr/bin/env node
/**
 * Phase 门控验证脚本
 * 用法：node scripts/phase-gate-validator.js ComponentName PhaseN
 *
 * 遵循 CONTRIBUTING.md 规范和分析报告建议3: Phase门控加强
 */

const fs = require('fs');
const path = require('path');

/**
 * 加载 checkpoint 文件
 */
function loadCheckpoint(componentName, phase) {
  const checkpointMap = {
    'Phase0': 'P0_initialization.json',
    'Phase1': 'P1_figma_data.json',
    'Phase2': 'P2_preview_build.json',
    'Phase3': 'P3_field_design.json',
    'Phase4': 'P4_panel_generation.json',
    'Phase5': 'P5_integration.json'
  };

  const filename = checkpointMap[phase];
  if (!filename) {
    throw new Error(`未知Phase: ${phase}`);
  }

  const checkpointPath = path.join(process.cwd(), componentName, 'checkpoints', filename);

  if (!fs.existsSync(checkpointPath)) {
    throw new Error(`Checkpoint 不存在: ${checkpointPath}`);
  }

  return JSON.parse(fs.readFileSync(checkpointPath, 'utf8'));
}

/**
 * Phase0 门控验证
 */
function validatePhase0Gate(componentName) {
  console.log(`\n🚦 Phase0 门控验证`);

  const checkpoint = loadCheckpoint(componentName, 'Phase0');

  const checks = [
    {
      name: 'Figma URL有效性',
      test: () => {
        return checkpoint.validation?.figmaUrlValid === true;
      }
    },
    {
      name: '必需字段完整性',
      test: () => {
        return checkpoint.validation?.requiredFieldsComplete === true;
      }
    },
    {
      name: '字段提取数量',
      test: () => {
        return checkpoint.extractedFields?.contentFieldsCount >= 5;
      }
    },
    {
      name: '质量评分',
      test: () => {
        return checkpoint.qualityMetrics?.overallScore >= 95;
      }
    }
  ];

  return runChecks('Phase0', checks);
}

/**
 * Phase1 门控验证
 */
function validatePhase1Gate(componentName) {
  console.log(`\n🚦 Phase1 门控验证`);

  const checkpoint = loadCheckpoint(componentName, 'Phase1');

  const checks = [
    {
      name: 'MCP调用成功',
      test: () => {
        return checkpoint.mcpCalls?.get_design_context?.status === 'success';
      }
    },
    {
      name: 'Blueprint字段覆盖率',
      test: () => {
        const fields = checkpoint.blueprintGeneration?.blueprintAligned?.totalFields || 0;
        return fields >= 20;
      }
    },
    {
      name: '数据完整性',
      test: () => {
        return checkpoint.qualityMetrics?.dataCompleteness >= 0.95;
      }
    }
  ];

  return runChecks('Phase1', checks);
}

/**
 * Phase2 门控验证（强化版）
 */
function validatePhase2Gate(componentName) {
  console.log(`\n🚦 Phase2 门控验证（强化版）`);

  const checkpoint = loadCheckpoint(componentName, 'Phase2');
  const root = process.cwd();

  const checks = [
    {
      name: 'preview-props-schema.json 存在',
      test: () => {
        const schemaPath = path.join(root, componentName, 'phase2/preview-props-schema.json');
        return fs.existsSync(schemaPath);
      }
    },
    {
      name: 'reference-component-comparison.json 存在 [强制检查点]',
      test: () => {
        const comparisonPath = path.join(root, componentName, 'phase2/reference-component-comparison.json');
        if (!fs.existsSync(comparisonPath)) {
          return false;
        }

        // 验证内容
        const comparison = JSON.parse(fs.readFileSync(comparisonPath, 'utf8'));
        return comparison.summary?.matchRate === 1.0 && comparison.summary?.allSpecialChecksPassed === true;
      },
      critical: true  // 标记为关键检查
    },
    {
      name: 'UI还原度 ≥95%',
      test: () => {
        return checkpoint.qualityMetrics?.uiRestorationRate >= 0.95;
      }
    },
    {
      name: 'Props结构有效',
      test: () => {
        return checkpoint.qualityMetrics?.propsStructureValid === true;
      }
    },
    {
      name: 'TypeScript编译通过',
      test: () => {
        return checkpoint.qualityMetrics?.typeScriptCompiles === true;
      }
    }
  ];

  return runChecks('Phase2', checks);
}

/**
 * Phase3 门控验证（强化版）
 */
function validatePhase3Gate(componentName) {
  console.log(`\n🚦 Phase3 门控验证（强化版）`);

  const checkpoint = loadCheckpoint(componentName, 'Phase3');
  const root = process.cwd();

  const checks = [
    {
      name: 'panel-reuse-analysis.json 存在 [强制检查点]',
      test: () => {
        const analysisPath = path.join(root, componentName, 'phase3/panel-reuse-analysis.json');
        if (!fs.existsSync(analysisPath)) {
          return false;
        }

        // 验证内容
        const analysis = JSON.parse(fs.readFileSync(analysisPath, 'utf8'));
        return typeof analysis.needsCustomPanel === 'boolean';
      },
      critical: true
    },
    {
      name: 'three-layer-validation.json 存在 [强制检查点]',
      test: () => {
        const validationPath = path.join(root, componentName, 'phase3/three-layer-validation.json');
        if (!fs.existsSync(validationPath)) {
          return false;
        }

        // 验证内容
        const validation = JSON.parse(fs.readFileSync(validationPath, 'utf8'));
        return validation.errors?.length === 0;
      },
      critical: true
    },
    {
      name: '字段覆盖率 100%',
      test: () => {
        return checkpoint.qualityMetrics?.fieldCoverageRate === 1.0;
      }
    },
    {
      name: 'EditFields一致性 100%',
      test: () => {
        return checkpoint.qualityMetrics?.editFieldsConsistency === 1.0;
      }
    }
  ];

  return runChecks('Phase3', checks);
}

/**
 * Phase4 门控验证
 */
function validatePhase4Gate(componentName) {
  console.log(`\n🚦 Phase4 门控验证`);

  const root = process.cwd();
  const decisionPath = path.join(root, componentName, 'phase4/execution-decision.json');

  if (!fs.existsSync(decisionPath)) {
    console.log(`  ⚠️  execution-decision.json 不存在，跳过Phase4验证`);
    return { passed: true, skipped: true };
  }

  const decision = JSON.parse(fs.readFileSync(decisionPath, 'utf8'));

  if (decision.executed === false) {
    console.log(`  ✅ Phase4已跳过（needsCustomPanel=false）`);
    return { passed: true, skipped: true };
  }

  const checkpoint = loadCheckpoint(componentName, 'Phase4');

  const checks = [
    {
      name: '自定义面板实现',
      test: () => {
        return checkpoint.qualityMetrics?.fieldCoverage >= 0.95;
      }
    },
    {
      name: '面板可编译',
      test: () => {
        return checkpoint.qualityMetrics?.typescript === 'pass';
      }
    }
  ];

  return runChecks('Phase4', checks);
}

/**
 * Phase5 门控验证（强化版）
 */
function validatePhase5Gate(componentName) {
  console.log(`\n🚦 Phase5 门控验证（强化版）`);

  const checkpoint = loadCheckpoint(componentName, 'Phase5');
  const root = process.cwd();

  const checks = [
    {
      name: 'validation-results.json 存在 [强制检查点]',
      test: () => {
        // 尝试两种可能的文件名
        const validationPath1 = path.join(root, componentName, 'phase5/validation-results.json');
        const validationPath2 = path.join(root, componentName, `phase5/${componentName}-validation-results.json`);

        let validationPath = null;
        if (fs.existsSync(validationPath1)) {
          validationPath = validationPath1;
        } else if (fs.existsSync(validationPath2)) {
          validationPath = validationPath2;
        } else {
          return false;
        }

        // 验证内容
        try {
          const results = JSON.parse(fs.readFileSync(validationPath, 'utf8'));
          const score = results.validationResults?.chainValidator?.score
                     || results.chainValidator?.score;
          return score >= 90;
        } catch (e) {
          console.error(`  ⚠️  解析 validation-results.json 失败: ${e.message}`);
          return false;
        }
      },
      critical: true
    },
    {
      name: 'ChainValidator分数 ≥90',
      test: () => {
        // 支持两种可能的字段路径
        const score = checkpoint.validationResults?.chainValidator?.score
                   || checkpoint.qualityMetrics?.chainValidatorScore;
        return score >= 90;
      }
    },
    {
      name: 'UI还原度 ≥95%',
      test: () => {
        return checkpoint.qualityMetrics?.uiRestorationRate >= 0.95;
      }
    },
    {
      name: 'LOCAL_TEST注册完整',
      test: () => {
        // 检查注册验证结果
        const regCheck = checkpoint.validationResults?.registration?.status === 'pass'
                      || checkpoint.registrationVerification?.LOCAL_TEST_COMPONENTS?.registered === true;
        return regCheck;
      }
    }
  ];

  return runChecks('Phase5', checks);
}

/**
 * 执行检查列表
 */
function runChecks(phaseName, checks) {
  let passed = 0;
  let failed = 0;
  const failures = [];

  checks.forEach(check => {
    try {
      const result = check.test();
      if (result) {
        console.log(`  ✅ ${check.name}`);
        passed++;
      } else {
        const marker = check.critical ? '🔴' : '❌';
        console.log(`  ${marker} ${check.name}`);
        failed++;
        failures.push({
          name: check.name,
          critical: check.critical || false
        });
      }
    } catch (error) {
      console.log(`  ❌ ${check.name} (检查失败: ${error.message})`);
      failed++;
      failures.push({
        name: check.name,
        error: error.message,
        critical: check.critical || false
      });
    }
  });

  const hasCriticalFailures = failures.some(f => f.critical);

  console.log(`\n  结果: ${passed}/${checks.length} 通过`);

  return {
    phase: phaseName,
    passed: passed === checks.length,
    passedCount: passed,
    failedCount: failed,
    totalChecks: checks.length,
    failures,
    hasCriticalFailures
  };
}

/**
 * 主验证函数
 */
function validatePhaseGate(componentName, phase) {
  console.log(`\n🔒 Phase门控验证 - ${componentName}`);
  console.log(`   Phase: ${phase}`);

  const validators = {
    'Phase0': validatePhase0Gate,
    'Phase1': validatePhase1Gate,
    'Phase2': validatePhase2Gate,
    'Phase3': validatePhase3Gate,
    'Phase4': validatePhase4Gate,
    'Phase5': validatePhase5Gate
  };

  const validator = validators[phase];
  if (!validator) {
    throw new Error(`不支持的Phase: ${phase}`);
  }

  const result = validator(componentName);

  console.log(`\n` + '='.repeat(60));

  if (result.skipped) {
    console.log(`✅ ${phase} 门控验证: 已跳过`);
    return 0;
  }

  if (result.passed) {
    console.log(`✅ ${phase} 门控验证: 通过`);
    return 0;
  } else {
    console.log(`❌ ${phase} 门控验证: 未通过 (${result.passedCount}/${result.totalChecks})`);

    if (result.hasCriticalFailures) {
      console.log(`\n🔴 关键检查失败，阻断Phase转换:`);
      result.failures
        .filter(f => f.critical)
        .forEach(f => console.log(`   - ${f.name}`));
    }

    console.log(`\n建议: 修复失败项后重新验证`);
    return 1;
  }
}

// CLI 执行
function main() {
  const componentName = process.argv[2];
  const phase = process.argv[3];

  if (!componentName || !phase) {
    console.error('❌ 参数缺失');
    console.error('用法: node scripts/phase-gate-validator.js ComponentName PhaseN');
    console.error('示例: node scripts/phase-gate-validator.js UsageTrendsProd2 Phase2');
    process.exit(1);
  }

  try {
    const exitCode = validatePhaseGate(componentName, phase);
    process.exit(exitCode);
  } catch (error) {
    console.error(`\n❌ 验证失败: ${error.message}`);
    console.error(error.stack);
    process.exit(1);
  }
}

main();
